package com.wontube.smr.bo.sites.fs.mp3skull;

import java.io.IOException;
import java.net.URL;
import java.util.UUID;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wontube.smr.bo.sites.fs.conf.FourShared;
import com.wontube.smr.client.model.vo.AudioFile;
import com.wontube.smr.client.model.vo.AudioFiles;
import com.wontube.smr.dao.bo.KeywordFilterDao;


/**
 * @author yuechao
 * 
 */
public final class Mp3SkullHtmlParser {
	private static final Logger logger = LoggerFactory.getLogger(Mp3SkullHtmlParser.class);

	/**
	 * 解析mp3skull
	 * 
	 * @param query
	 * @param pageIndex
	 *            从1开始
	 * @return
	 */
	public static AudioFiles parse(String query, int pageIndex) {
		AudioFiles files = new AudioFiles();

		if (!FourShared.fs.isUseMp3Skull() || isNotAllEnglish(query)) {
			return files;
		}

		while (query.contains("  ")) {
			query = query.replace("  ", " ");
		}
		
		if (!KeywordFilterDao.isKeywordCopyright(KeywordFilterDao.keyTypeMusic, query)) {
			files.setCopyright(false);
			return files;
		}

		query = query.replace(' ', '_').replace(".", "");
		String url = "http://mp3skull.com/mp3/" + query + ".html";

		try {
			files = Mp3SkullHtmlParser.internalParse(url, pageIndex);
			files.setQuery(query);
		} catch (Exception e) {
			logger.error(e.toString());
			files = new AudioFiles();
		}

		return files;
	}

	private static AudioFiles internalParse(String url, int pageIndex) throws IOException {
		AudioFiles files = new AudioFiles();
		URL uri = new URL(url);

		Document doc = Jsoup.parse(uri, 20000);
		Elements elements = doc.select("#song_html");

		files.setPageSize(10);
		int start = files.getPageSize() * (pageIndex - 1);
		files.setTotalCount(elements.size());
		files.setStart(start);

		int pageCount = (int) Math.ceil(elements.size() / (double) files.getPageSize());
		files.setPageCount(pageCount);

		int end = start + 10;
		if (end > elements.size()) {
			end = elements.size();
		}

		//SimpleAPI api = new SimpleAPI();
		
		for (int i = start; i < end; i++) {
			Element element = elements.get(i);
			Element divSong = element.select("#right_song").get(0);
			String filename = divSong.select("#right_song > div").get(0).text();
			if (filename.endsWith("mp3")) {
				filename = filename.substring(0, filename.length() - 3).trim();
			}
			if (filename.endsWith(".")) {
				filename += "mp3";
			} else {
				filename += ".mp3";
			}
			Elements links = divSong.select("#right_song > div a").eq(0);
			if (links.size() < 1) {
				continue;
			}

			Element linkTag = links.get(0);

			AudioFile file = new AudioFile();
			files.getFiles().add(file);
			file.setId(UUID.randomUUID().toString());
			String link = linkTag.attr("href");
			//link = api.getDirectLink(link);
			file.setDownloadUrl(link);
			file.setFilename(filename);
			String[] args = element.select("#song_html > .left").text().split("[ ]");

			for (int j = 1; j < args.length; j++) {
				String text = args[j];
				if ("kbps".equals(text)) {
					String b = args[j - 1];
					int bitrate = Integer.parseInt(b);
					file.setBitrate(bitrate);
				} else if (text.contains(":")) {
					String m = text;
					String[] minsArgs = m.split("[:]");
					int seconds = 0;
					int k = 1;
					for (int index = minsArgs.length - 1; index >= 0; index--) {
						int value = Integer.parseInt(minsArgs[index].trim());
						seconds += k * value;
						k *= 60;
					}
					file.setDuration(seconds);
				} else if ("mb".equals(text)) {
					String size = args[j - 1] + " " + text;
					file.setSize(size);
				}
			}
		}

		return files;
	}

	private static boolean isNotAllEnglish(String s) {
		if (s == null) {
			return false;
		}

		return s.getBytes().length != s.length();
	}
}
